<template>
  <div class="flexLeft img-uploader" v-if="type == 'image'">
    <el-upload :http-request="uploadImgFun" :show-file-list="false" :on-success="handleImageUploadSuccess"
      :before-upload="beforeImageUpload" accept="image/*">
      <img v-if="imageUrl || pImgUrl" :src="imageUrl || pImgUrl" class="img" />
      <div v-else>
        <el-icon class="img-uploader-icon">
          <Plus />
        </el-icon>
        <div class="img-upload-tip">
          {{ tip }}
        </div>
      </div>
    </el-upload>
  </div>
  <div class="flexLeft " v-if="type == 'video'">
    <el-upload :show-file-list="true" class="upload-video" accept="video/*" :http-request="uploadFun"
      :before-upload="beforeVideoUpload" :file-list="fileList" :beforeRemove="beforeRemove" :on-preview="toPreviewVideo">
      <el-button type="primary" size="small">{{ btnText }}</el-button>
      <div class="upload-tip">
        {{ tip }}
      </div>
      <template #tip v-if="isUploading">
        <div class="upload-progress">
          <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success" />
        </div>
      </template>
    </el-upload>
  </div>
  <el-dialog v-model="dialogVisible" class="video-preview" @close="closePreview">
    <video :src="videoUrl" id="myvideo" controls ref="myvideo"></video>
  </el-dialog>
</template>
<script setup>
import { ref } from "vue"
import { ElLoading, ElMessage } from "element-plus";
import cos from '@/utils/cos';
import { useCommonStore } from '@/stores';
import { uploadImg, getCredentials } from '@/api/uploader.js'
import { ElMessageBox } from 'element-plus';


const imageUrl = ref('');//图片地址

const percentage = ref(0);//进度条

const isUploading = ref(false);//上传视频显示进度条

const commonStore = useCommonStore();

// 视频预览
const dialogVisible = ref(false);
const videoUrl = ref('');

const myvideo = ref(null);

const props = defineProps({
  btnText: {
    type: String,
    default: '请选择文件'
  },
  type: {
    type: String,
    default: 'imgae'
  },
  tip: {
    type: String,
    default: ''
  },
  pImgUrl: {//缩略图
    type: String,
    default: ''
  },
  fileList: {//上传文件列表
    type: Array,
    default: () => []
  }
})


const emit = defineEmits({
  'imgUploadSuc': null,
  'videoUploadSuc': null,
  'removeFile': null
})

// methods
const handleImageUploadSuccess = (res, file) => {
  console.log('upload img success', res, file);
}

const beforeImageUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 3) {
    ElMessage.error('图片最大不超过3MB!')
    return false
  }
  return true
}

const uploadImgFun = async (rawFile) => {
  const loading = ElLoading.service({
    lock: true,
    text: '上传中',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    const fromData = new FormData()
    fromData.append('files', rawFile.file)
    const res = await uploadImg(fromData)
    console.log(res);
    if (res.code === 1000) {
      imageUrl.value = res.data.image_url
      emit('imgUploadSuc', res.data.image_path)
    }
    loading.close()
  } catch (error) {
    ElMessage.error('图片上传失败')
    console.log(error);
    loading.close()
  }

}


const beforeVideoUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 100) {
    ElMessage.error('视频最大不超过100MB!')
    return false
  }
  return true
}

const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `取消上传 ${uploadFile.name} ?`
  ).then(
    () => {//确认删除
      emit('removeFile', uploadFile.uid)
      return true
    },
    () => false
  )
}


const toPreviewVideo = (videoInfo) => {
  if(videoInfo.url === ''){
    return ;
  }
  dialogVisible.value = true;
  videoUrl.value = videoInfo.url;
}

const closePreview = () => {
  myvideo.value.pause();
  myvideo.value.currentTime = 0;
  dialogVisible.value = false;
  videoUrl.value = '';
  myvideo.value.src = '';
}

const uploadFun = async (rawFile) => {
  console.log(rawFile);
  let options = {
    Bucket: 'overseas-us-1303638958',
    Region: 'na-ashburn'
  }
  const res = await getCredentials({ ...options });
  let cbOptions = null;
  if (res.code === 1000) {
    const data = res.data;
    cbOptions = {
      TmpSecretId: data.credentials.tmpSecretId,
      TmpSecretKey: data.credentials.tmpSecretKey,
      XCosSecurityToken: data.credentials.sessionToken,
      ExpiredTime: data.expiredTime,
      StartTime: data.startTime,
      Key: data.key
    }
    commonStore.$patch({//后续使用
      videoOptions: cbOptions
    })
  }
  Object.assign(options, cbOptions);
  try {
    isUploading.value = true
    cos.uploadFile({
      ...options,
      Body: rawFile.file,
      SliceSize: 1024 * 1024 * 20,//大于20M的文件分片上传
      onProgress: function (progressData) {           /* 非必须 */
        percentage.value = Math.floor(progressData.percent * 100);
      },
      onFileFinish: function (err, data, options) {   /* 非必须 */
        ElMessage.success('上传' + (err ? '失败' : '完成'));
      },

    }, function (err, data) {
      console.log('err', err);
      console.log('data', data);
      if (data.statusCode === 200) {
        emit('videoUploadSuc', cbOptions.Key)
      }
    });
  } catch (error) {
    console.log(error);
    ElMessage.error('视频上传失败')
  }

}

</script>
<style lang="less" scoped>
.img-uploader {
  .img {
    width: 178px;
    height: 178px;
    display: block;
  }

  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }

  .el-icon.img-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  .img-upload-tip {
    position: absolute;
    bottom: 0;
    width: 178px;
    line-height: 20px;
    text-align: center;
    color: var(--el-color-info-light-3);
  }

}

.upload-tip {
  font-size: 12px;
  color: var(--el-color-info-light-3);
  padding-left: 20px;
}

:deep(.el-icon--close-tip) {
  display: none !important;
}
#myvideo{
  max-height: 80%;
  max-width: 50%;
}
</style>